import streamlit as st
import cv2
import numpy as np
import sqlite3
import datetime


# 初始化数据库（简化版）
def init_db():
    conn = sqlite3.connect('image_history.db')
    c = conn.cursor()
    c.execute('''
        CREATE TABLE IF NOT EXISTS process_history (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            filename TEXT,
            process_type TEXT,
            process_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ''')
    conn.commit()
    conn.close()


# 保存处理记录（简化版）
def save_history(filename, process_type):
    conn = sqlite3.connect('image_history.db')
    c = conn.cursor()
    c.execute('''
        INSERT INTO process_history (filename, process_type) 
        VALUES (?, ?)
    ''', (filename, process_type))
    conn.commit()
    conn.close()


# 获取历史记录（简化版）
def get_history():
    conn = sqlite3.connect('image_history.db')
    c = conn.cursor()
    c.execute('SELECT filename, process_type, process_time FROM process_history ORDER BY process_time DESC LIMIT 10')
    records = c.fetchall()
    conn.close()
    return records


# 初始化数据库
init_db()

# 页面设置
st.set_page_config(page_title="简单图片处理", page_icon="🖼️")
st.title("🖼️ 简单图片处理")

# 上传图片
uploaded_file = st.file_uploader("选择图片", type=['jpg', 'png', 'jpeg'])

if uploaded_file is not None:
    # 转换为OpenCV格式
    file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
    image = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)

    # 显示原图
    st.image(image, channels="BGR", caption="原图", use_column_width=True)

    # 处理选项
    st.subheader("处理选项")
    option = st.selectbox("选择处理效果",
                          ["请选择", "灰度图", "模糊效果", "颜色反转"])

    if option != "请选择":
        processed_image = image.copy()

        if option == "灰度图":
            processed_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            processed_image = cv2.cvtColor(processed_image, cv2.COLOR_GRAY2BGR)
            save_history(uploaded_file.name, "灰度图")

        elif option == "模糊效果":
            processed_image = cv2.GaussianBlur(image, (15, 15), 0)
            save_history(uploaded_file.name, "模糊效果")

        elif option == "颜色反转":
            processed_image = cv2.bitwise_not(image)
            save_history(uploaded_file.name, "颜色反转")

        # 显示处理结果
        st.image(processed_image, channels="BGR", caption=f"{option}", use_column_width=True)
        st.success(f"已完成 {option} 处理！")

# 显示历史记录
st.sidebar.title("📊 处理历史")
history = get_history()

if history:
    st.sidebar.subheader("最近10条记录")
    for record in history:
        filename, process_type, process_time = record
        st.sidebar.write(f"📌 {filename}")
        st.sidebar.write(f"🔧 {process_type}")
        st.sidebar.write(f"⏰ {process_time[:16]}")
        st.sidebar.write("---")
else:
    st.sidebar.info("暂无处理记录")

# 清空历史记录按钮
if st.sidebar.button("清空历史记录"):
    conn = sqlite3.connect('image_history.db')
    c = conn.cursor()
    c.execute('DELETE FROM process_history')
    conn.commit()
    conn.close()
    st.sidebar.success("历史记录已清空！")
    st.rerun()